package com.xinchao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinchao.constant.PageConstant;
import com.xinchao.dao.AdvertiserMapper;
import com.xinchao.exception.ServiceException;
import com.xinchao.model.Advertiser;
import com.xinchao.model.dto.AdvertiserListDTO;
import com.xinchao.model.dto.AdvertiserSelectDTO;
import com.xinchao.model.page.PageInfo;
import com.xinchao.service.AdvertisementService;
import com.xinchao.service.AdvertiserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author dxy
 * @date 2018/9/18 18:35
 */
@Service(value = "advertiserService")
public class AdvertiserServiceImpl implements AdvertiserService {
	@Autowired
	private AdvertiserMapper advertiserMapper;

	/**
	 * 获取广告主列表
	 * @param advertiserName   广告主名称
	 * @param pageNum             当前页
	 * @param pageSize            每页条数
	 * @return PageInfo<AdvertiserListDTO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public PageInfo<AdvertiserListDTO> listAdvertiser(String advertiserName, Integer pageNum, Integer pageSize) {
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<AdvertiserListDTO> page = advertiserMapper.listAdvertiser(advertiserName);
		PageInfo<AdvertiserListDTO> pageInfo = new PageInfo<>();
		if (page == null) {
			return pageInfo;
		}
		pageInfo.setPageNum(page.getPageNum());
		pageInfo.setPageSize(page.getPageSize());
		pageInfo.setTotal(page.getTotal());
		pageInfo.setList(page.getResult());
		return pageInfo;
	}

	/**
	 * 获取广告选择列表
	 * @return List<AdvertiserSelectDTO>
	 */
	@Override
	public List<AdvertiserSelectDTO> listAdvertiserSelect() {
		return advertiserMapper.listAdvertiserSelect();
	}

	/**
	 * 通过账号获取广告主
	 * @param userName 账号
	 * @return Advertiser
	 * @throws ServiceException
	 */
	@Override
	public Advertiser getAdvertiserByUserName(String userName) throws ServiceException {
		if (StringUtils.isBlank(userName)) {
			throw new ServiceException("账号不能为空");
		}
		return advertiserMapper.getAdvertiserByUserName(userName);
	}

	/**
	 * 通过广告主名称获取广告主ID列表
	 *
	 * @param advertiserName 广告主名称
	 * @return List<Long>
	 * @throws ServiceException
	 */
	@Override
	public List<Long> listAdvertiserIdByAdvertiserName(String advertiserName) throws ServiceException {
		if (StringUtils.isBlank(advertiserName)) {
			throw new ServiceException("输入参数不能为空");
		}
		return advertiserMapper.listAdvertiserIdByAdvertiserName(advertiserName);
	}
}
